package gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import commands.LoginCheckCommand;

import containers.StudentContainer;
import dbadapters.ChangeStudentdb;
import dbadapters.checkConnection;
import entities.CoSigner;
import entities.FinancialInfo;
import entities.Student;

/**
 * 
 * @author eks691
 * 
 */
public class EmployeeCosignerChangeInfoPanel extends JPanel {
	protected PersonalInfoPanel lpanel;

	protected FinancialInfoPanel lpanel2;

	private Student std;
	private CoSigner cosigner;
	private int Id;
	private int employeeId;

	public EmployeeCosignerChangeInfoPanel(int sId, int eId) {

		Id = sId;
		employeeId = eId;
		lpanel = new PersonalInfoPanel();
		lpanel.setMaximumSize(lpanel.getPreferredSize());
		lpanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		lpanel.setAlignmentY(Component.TOP_ALIGNMENT);
		add(lpanel);

		lpanel2 = new FinancialInfoPanel();
		lpanel2.setMaximumSize(lpanel2.getPreferredSize());
		lpanel2.setAlignmentX(Component.LEFT_ALIGNMENT);
		lpanel2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		add(lpanel2);

		JButton change = new JButton("Submit Changes");
		change.setAlignmentY(Component.BOTTOM_ALIGNMENT);

		add(change);

		ApplyListener listener = new ApplyListener();
		change.addActionListener(listener);

		JButton back = new JButton("Back");
		back.setAlignmentX(Component.BOTTOM_ALIGNMENT);
		BackListener backListener = new BackListener();
		back.addActionListener(backListener);
		add(back);

		std = null;
		HashMap<Integer, Student> students = StudentContainer.dictionary();

		if (students.containsKey(sId) == true) {
			std = students.get(sId);
			cosigner = std.getLoan().getCosigner();
		}

		lpanel.nameField.setValue(cosigner.getName());
		lpanel.birthdateField.setValue(cosigner.getBirthdateAsString());
		lpanel.addressField.setValue(cosigner.getAddress());
		lpanel.phonenumberField.setValue(cosigner.getPhoneNumber());
		lpanel.emailField.setValue(cosigner.getEmail());
		lpanel2.personalField.setValue(Float.toString(cosigner
				.getFinancialInfo().getPersonalIncome()));
		lpanel2.householdField.setValue(Float.toString(cosigner
				.getFinancialInfo().getHouseholdIncome()));
		lpanel2.taxField.setValue(Float.toString(cosigner.getFinancialInfo()
				.getTaxableEarnings()));
		lpanel2.childField.setValue(Float.toString(cosigner.getFinancialInfo()
				.getChildSupport()));
		lpanel2.scholarField.setValue(Float.toString(cosigner
				.getFinancialInfo().getScholarship()));
		lpanel2.monthlyExpensesField.setValue(Float.toString(cosigner
				.getFinancialInfo().getMonthlyExpenses()));
	}

	private class BackListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent event) {
			getTopLevelAncestor().setVisible(false);
			MainMenuFrame frame = new MainMenuFrame(
					LoginCheckCommand.UserType.EMPLOYEE, employeeId);
			frame.setVisible(true);
			EmployeeCosignerInfoPanel newPanel = new EmployeeCosignerInfoPanel(
					Id, employeeId);
			frame.changePanel(newPanel);
		}
	}

	private class ApplyListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent event) {
			// sort out filled out info to create a new student and place
			// him/her in container

			boolean isValid = true; // manage if input to application form is
			// valid or not
			String errorString = ""; // error message if needed

			String studentName = lpanel.nameField.getValueAsString();
			String remainingJunk = studentName.replaceAll("[a-zA-Z ]", ""); // check
			// if
			// input
			// is
			// alphabetic
			if (remainingJunk.length() > 0 || studentName.length() == 0) {
				errorString += "Invalid input for Name\n";
				isValid = false;
			}

			// get birthdate info in format MM/dd/yyyy
			String studentBirthdate = lpanel.birthdateField.getValueAsString();
			remainingJunk = studentBirthdate.replaceAll("[0-9/]", "");
			// check for proper format
			boolean isValidDate = studentBirthdate
					.matches("[0-1][0-9]/[0-3][0-9]/[0-2][90][0-9][0-9]");
			if (!isValidDate || remainingJunk.length() > 0) {
				errorString += "Invalid input for birthdate, should be mm/dd/yyyy\n";
				isValid = false;
			}

			String studentAddress = lpanel.addressField.getValueAsString();
			remainingJunk = studentAddress.replaceAll("[a-zA-Z.0-9 ]", "");
			if (remainingJunk.length() > 0 || studentAddress.length() == 0) {
				errorString += "Invalid input for Address\n";
				isValid = false;
			}

			String studentPhone = lpanel.phonenumberField.getValueAsString();
			remainingJunk = studentPhone.replaceAll("[0-9 ()-]", "");
			if (remainingJunk.length() > 0 || studentPhone.length() == 0) {
				errorString += "Invalid input for Phone Number\n";
				isValid = false;
			}

			String studentEmail = lpanel.emailField.getValueAsString();
			remainingJunk = studentEmail.replaceAll("[a-zA-Z0-9.@()-]", "");
			if (remainingJunk.length() > 0 || studentEmail.length() == 0) {
				errorString += "Invalid input for e-mail\n";
				isValid = false;
			}

			float studentPersonalIncome = 0;
			try {
				studentPersonalIncome = lpanel2.personalField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentPersonalIncome = 0;
			}

			if (studentPersonalIncome < 0) {
				isValid = false;
				errorString += "Personal Income must be positive\n";
			}

			float studentHouseholdIncome = 0;
			try {
				studentHouseholdIncome = lpanel2.householdField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentHouseholdIncome = 0;
			}

			if (studentHouseholdIncome < 0) {
				isValid = false;
				errorString += "Household Income must be positive\n";
			}

			float studentTaxIncome = 0;
			try {
				studentTaxIncome = lpanel2.taxField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentTaxIncome = 0;
			}

			if (studentTaxIncome < 0) {
				isValid = false;
				errorString += "Taxable Income must be positive\n";
			}

			float studentChildSupport = 0;
			try {
				studentChildSupport = lpanel2.childField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentChildSupport = 0;
			}

			if (studentChildSupport < 0) {
				isValid = false;
				errorString += "Child Support must be positive\n";
			}

			float studentMonthlyExpenses = 0;
			try {
				studentMonthlyExpenses = lpanel2.monthlyExpensesField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentMonthlyExpenses = 0;
			}

			if (studentMonthlyExpenses < 0) {
				isValid = false;
				errorString += "Monthly Expenses must be positive\n";
			}

			if (!isValid) {
				JFrame myFrame = new JFrame();
				JOptionPane.showMessageDialog(myFrame, errorString);
			} else {
				// student and loan are ready to be built and placed into the
				// system

				cosigner.setAddress(studentAddress);
				cosigner.setBirthdate(studentBirthdate);
				cosigner.setEmail(studentEmail);
				cosigner.setName(studentName);
				cosigner.setPhoneNumber(studentPhone);

				FinancialInfo myFinances = cosigner.getFinancialInfo();
				myFinances.setChildSupport(studentChildSupport);
				myFinances.setHouseholdIncome(studentHouseholdIncome);
				myFinances.setPersonalIncome(studentPersonalIncome);
				myFinances.setTaxableEarnings(studentTaxIncome);
				myFinances.setMonthlyExpenses(studentMonthlyExpenses);

				cosigner.setFinancialInfo(myFinances);

				// update student in db if possible
				checkConnection c = new checkConnection();

				if (c.isConnectionValid()) {
					new ChangeStudentdb(std);
				} else {
					System.out.println(c.getErrorMessage());
				}

				// update in container
				if (StudentContainer.dictionary().containsKey(Id) == true) {
					Student nStudent = StudentContainer.dictionary().get(Id);
					StudentContainer.dictionary().remove(Id);
					StudentContainer.dictionary().put(Id, std);
				}
				JFrame myFrame = new JFrame();
				JOptionPane.showMessageDialog(myFrame, "Success!");
				myFrame.setVisible(false);

				// back to displaying information for employee
				getTopLevelAncestor().setVisible(false);
				MainMenuFrame frame = new MainMenuFrame(
						LoginCheckCommand.UserType.EMPLOYEE, employeeId);
				frame.setVisible(true);
				EmployeeCosignerInfoPanel newPanel = new EmployeeCosignerInfoPanel(
						Id, employeeId);
				frame.changePanel(newPanel);
			}
		}
	}

	private static final long serialVersionUID = 1L;

}